var express = require('express');
var router = express.Router();
let { UserModel } = require('../db/index')

const alipaySdk = require('../alipay')
const AlipayFormData = require('alipay-sdk/lib/form').default
const axios = require("axios");

// 支付接口
router.post('/payment', async (req, res) => {
  try {
    const { orderId, price, name } = req.body;

    // 参数验证
    if (!orderId || !price || !name) {                                                                      
      return res.json({
        code: 400,
        success: false,
        msg: "缺少必要参数",
        redirectUrl: "http://localhost:5173/app/home" // 跳转回支付页面
      });
    }

    const formData = new AlipayFormData();
    formData.setMethod("get");

    const bizContent = {
      out_trade_no: orderId,
      product_code: "FAST_INSTANT_TRADE_PAY",
      total_amount: price,
      subject: name,
      body: "商品详情",
    };
    formData.addField("bizContent", bizContent);

    // 配置支付成功和失败的返回页面
    const frontendUrl = "http://localhost:5173/app/home"; // 前端支付页面地址
    formData.addField("returnUrl", frontendUrl);

    let paymentUrl;
    try {
      paymentUrl = await alipaySdk.exec(
        "alipay.trade.wap.pay",
        {},
        { formData }
      );
    } catch (alipayError) {
      console.error('alipaySdk.exec 错误:', alipayError);
      return res.json({
        code: 501,
        success: false,
        msg: "alipaySdk.exec 调用失败",
        error: alipayError && alipayError.message ? alipayError.message : alipayError,
        redirectUrl: frontendUrl
      });
    }

    res.json({
      code: 200,
      success: true,
      msg: "支付中",
      paymentUrl,
    });
  } catch (error) {
    console.error('支付接口错误:', error);
    res.json({
      code: 500,
      success: false,
      msg: "支付接口异常",
      error: error && error.message ? error.message : error,
      redirectUrl: "http://localhost:5173/app/home" // 跳转回支付页面
    });
  }
});

// 支付查询接口
router.post('/paymentQuery', async (req, res) => {
  try {
    const { out_trade_no, trade_no } = req.body;

    if (!out_trade_no && !trade_no) {
      return res.json({
        code: 400,
        success: false,
        msg: "订单号或交易号至少需要一个",
        redirectUrl: "http://localhost:5173/app/home" // 跳转回支付页面
      });
    }

    const formData = new AlipayFormData();
    formData.setMethod("get");

    const bizContent = {
      out_trade_no,
      trade_no
    };
    formData.addField("bizContent", bizContent);

    const queryUrl = await alipaySdk.exec(
      "alipay.trade.query",
      {},
      { formData }
    );

    const { data } = await axios.get(queryUrl);
    const response = data.alipay_trade_query_response;

    if (response.code === '10000') {
      switch (response.trade_status) {
        case 'WAIT_BUYER_PAY':
          return res.json({
            code: 10001,
            success: false,
            msg: "支付宝有交易记录，没付款",
            redirectUrl: "http://localhost:5173/app/home" // 跳转回支付页面
          });
        case 'TRADE_FINISHED':
        case 'TRADE_SUCCESS':
          return res.json({
            code: 10002,
            success: true,
            msg: "交易完成",
            redirectUrl: "http://localhost:5173/app/home" // 跳转回支付页面
          });
        case 'TRADE_CLOSED':
          return res.json({
            code: 10003,
            success: false,
            msg: "交易关闭",
            redirectUrl: "http://localhost:5173/app/home" // 跳转回支付页面
          });
      }
    }

    if (response.code === '40004') {
      return res.json({
        code: 40004,
        success: false,
        msg: "交易不存在",
        redirectUrl: "http://localhost:5173/app/home" // 跳转回支付页面
      });
    }

    return res.json({
      code: 50001,
      success: false,
      msg: "查询失败",
      redirectUrl: "http://localhost:5173/app/home" // 跳转回支付页面
    });
  } catch (error) {
    console.error('查询接口错误:', error);
    return res.json({
      code: 50000,
      success: false,
      msg: "交易查询失败",
      redirectUrl: "http://localhost:5173/app/home" // 跳转回支付页面
    });
  }
});

// 登录接口
router.post('/login', async (req, res) => {
  const { userName, passWord } = req.body;
  const user = await UserModel.findMany({ userName, passWord });
  if (user) {
    res.json({ success: true, user: { userName: user.userName } });
  } else {
    res.json({ success: false, message: '账号或密码错误' });
  }
})

module.exports = router;